﻿using System;
using System.Threading;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Zadanie4
{
    public delegate void ChangedEventHandler();

    class Problem
    {
        private bool running = false;
        public event ChangedEventHandler Changed;

        public int PassingNorthbound
        {
            get
            {
                return bridge.northboundCount;
            }
        }
        public int PassingSouthbound
        {
            get
            {
                return bridge.southboundCount;
            }
        }
        public int WaitingNorthbound
        {
            get
            {
                return bridge.enterNorthboundQueue.Count;
            }
        }
        public int WaitingSouthbound
        {
            get
            {
                return bridge.enterSouthboundQueue.Count;
            }
        }

        private Thread[] northboundThreads, southboundThreads;
        private const int N = 10;
        private Brigde bridge = new Brigde();

        private void Northbound()
        {
            Random rng = new Random();

            while (true)
            {
                bridge.EnterNorthbound();

                if (Changed != null) Changed();
                Thread.Sleep(500 + rng.Next(2000));

                bridge.ExitNorthbound();

                if (Changed != null) Changed();
                Thread.Sleep(1000 + rng.Next(4000));
            }
        }

        private void Southbound()
        {
            Random rng = new Random();

            while (true)
            {
                bridge.EnterSouthbound();

                if (Changed != null) Changed();
                Thread.Sleep(500 + rng.Next(2000));

                bridge.ExitSouthbound();

                if (Changed != null) Changed();
                Thread.Sleep(1000 + rng.Next(4000));
            }
        }

        public void Run()
        {
            northboundThreads = new Thread[N];
            southboundThreads = new Thread[N];

            for (int i = 0; i < N; i++)
            {
                northboundThreads[i] = new Thread(new ThreadStart(Northbound));
                southboundThreads[i] = new Thread(new ThreadStart(Southbound));

                northboundThreads[i].Start();
                southboundThreads[i].Start();
            }

            bridge.Run();

            running = true;
        }

        public void Stop()
        {
            if (!running) return;

            bridge.Stop();

            for (int i = 0; i < N; i++)
            {
                northboundThreads[i].Abort();
                southboundThreads[i].Abort();
            }
        }
    }
}
